﻿using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf.codec;

public partial class User_Controls_CommonControls : System.Web.UI.UserControl
{
    public string GridviewControlId
    { 
        get;
        set;
    }
    public string HideColumns
    {
        get;
        set;
    }
    Hashtable htControls = new Hashtable();
    protected void Page_Load(object sender, System.EventArgs e)
    {
       GridView grd = (GridView)this.Parent.FindControl(GridviewControlId);
       //lnkbtnPrint.Attributes.Add("onclick", "javascript:doPrint('"+grd.Parent.ClientID+"');");
    }
    protected void lnkbtnexcel_Click(object sender, EventArgs e)
    {
        GridView grd = (GridView)this.Parent.FindControl(GridviewControlId);
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.ContentType = "application/ms-excel";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        HtmlForm frm = new HtmlForm();
        grd.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        if (HideColumns != string.Empty && HideColumns != null)
        {
            if (HideColumns.Contains(","))
            {
                string[] columns = HideColumns.Split(',');
                for (int i = 0; i < columns.Length; i++)
                {
                    grd.Columns[Convert.ToInt16(columns[i])].Visible = false;
                }
            }
            else
            {
                grd.Columns[Convert.ToInt16(HideColumns)].Visible = false;
            }
        }
        grd.Columns[grd.Columns.Count - 1].Visible = false;
        //grd.Columns[grd.Columns.Count - 2].Visible = false;        
        frm.Controls.Add(grd);
        frm.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    protected void lkbtnpdf_Click(object sender, EventArgs e)
    {
        //GridView grd = (GridView)this.Parent.FindControl(GridviewControlId);
        //if (HideColumns != string.Empty && HideColumns != null)
        //{
        //    if (HideColumns.Contains(","))
        //    {
        //        string[] columns = HideColumns.Split(',');
        //        for (int i = 0; i < columns.Length; i++)
        //        {
        //            grd.Columns[Convert.ToInt16(columns[i])].Visible = false;
        //        }
        //    }
        //    else
        //    {
        //        grd.Columns[Convert.ToInt16(HideColumns)].Visible = false;
        //    }
        //}

        //int columncount = grd.Columns.Count;
        //int rowcount = grd.Rows.Count;
        //iTextSharp.text.Table grdTable = new iTextSharp.text.Table(columncount);
        //grdTable.BorderWidth = 1;
        //grdTable.BorderColor = new Color(0, 0, 0);
        //grdTable.Cellpadding = 2;
        //grdTable.Cellspacing = 0;
        //Font normaltext = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL);
        //Font boldtext = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD);
        //for (int x = 0; x < columncount; x++)
        //{
        //    string cellText = Server.HtmlDecode(grd.HeaderRow.Cells[x].Text);
        //    Phrase phhead = new Phrase(cellText, boldtext);
        //    Paragraph para = new Paragraph(phhead);
        //    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(para);
        //    grdTable.AddCell(cell);
        //}
        //for (int i = 0; i < grd.Rows.Count; i++)
        //{
        //    if (grd.Rows[i].RowType == DataControlRowType.DataRow)
        //    {
        //        for (int j = 0; j < grd.Columns.Count; j++)
        //        {
        //            if (grd.Columns[j] is TemplateField)
        //            {
        //                string cellText = "";
        //                //if (grd.Rows[i].Cells[j].Controls[0].GetType().ToString() == "System.Web.UI.LiteralControl")
        //                //{
        //                //    Literal lc = (Literal)grd.Rows[i].Cells[j].Controls[0];
        //                //    cellText = lc.Text;
        //                //}
        //                //else
        //                //{
        //                DataBoundLiteralControl lc = (DataBoundLiteralControl)grd.Rows[i].Cells[j].Controls[0];
        //                cellText = lc.Text;
        //                //}
        //                Phrase phhead = new Phrase(cellText, normaltext);
        //                Paragraph para = new Paragraph(phhead);
        //                iTextSharp.text.Cell cell = new iTextSharp.text.Cell(para);
        //                grdTable.AddCell(cell);
        //            }
        //            else
        //            {
        //                string cellText = Server.HtmlDecode(grd.Rows[i].Cells[j].Text);
        //                Phrase phhead = new Phrase(cellText, normaltext);
        //                Paragraph para = new Paragraph(phhead);
        //                iTextSharp.text.Cell cell = new iTextSharp.text.Cell(para);
        //                grdTable.AddCell(cell);
        //            }
        //        }
        //    }
        //}
        //Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        //PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        //pdfDoc.Open();
        //pdfDoc.Add(grdTable);
        //pdfDoc.Close();
        //Response.ContentType = "application/pdf";
        //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.Write(pdfDoc);
        //Response.End(); 


        GridView grd = (GridView)this.Parent.FindControl(GridviewControlId);

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();        
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        grd.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        grd.Columns[grd.Columns.Count - 1].Visible = false;
        grd.Columns[grd.Columns.Count - 2].Visible = false;
        Font normaltext = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL);      
        for (int i = 0; i < grd.Rows.Count; i++)
        {
            //System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)grd.Rows[i].Cells[grd.Columns.Count - 2].FindControl("imgitem");
            //string imagepath = img.ImageUrl;
            //iTextSharp.text.Image imgsize = iTextSharp.text.Image.GetInstance(imagepath);
            ////imgsize.ScalePercent(60f);
            //imgsize.ScaleToFit(60f, 60f);                       
        }               
        grd.AllowPaging = false;
        frm.DataBind();
        frm.Controls.Add(grd);
        frm.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        sr.ReadLine();
        //Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        Document pdfDoc = new Document(PageSize.A2.Rotate(),5f,5f,10f,10f);        
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);        
        pdfDoc.Open();
        htmlparser.Parse(sr);
        Response.Write(pdfDoc);
        pdfDoc.Close();
        Response.End();  
    }
    protected void lnkbtnPrint_Click(object sender, EventArgs e)
    {
        //GridView grdDisplay = (GridView)this.Parent.FindControl(GridviewControlId);
       // PrintWebControl(grdDisplay, string.Empty);
        //StringWriter stringWrite = new StringWriter();
        //HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        //HtmlForm frm = new HtmlForm();
        //grdDisplay.Parent.Controls.Add(frm);
        //frm.Attributes["runat"] = "server";
        //frm.Controls.Add(grdDisplay);
        //frm.RenderControl(htmlWrite);
        //grdDisplay.PagerSettings.Visible = false;
      
        //string gridHTML = stringWrite.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");
        //StringBuilder sb = new StringBuilder();
        //sb.Append("<script type = 'text/javascript'>");
        //sb.Append("window.onload = new function(){");
        //sb.Append("var printWin = window.open('', '', 'left=0");
        //sb.Append(",top=0,width=1000,height=600,status=0');");
        //sb.Append("printWin.document.write(\"");
        //sb.Append(gridHTML);
        //sb.Append("\");");
        //sb.Append("printWin.document.close();");
        //sb.Append("printWin.focus();");
        //sb.Append("printWin.print();");
        //sb.Append("printWin.close();};");
        //sb.Append("</script>");
        ////ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
        //Response.Write(sb.ToString());
        //Response.End();
        //grdDisplay.PagerSettings.Visible = true;
      
    } 
    private void PrepareGridViewForExport(Control gv)
    {
        Literal l = new Literal();
        for (int i = 0; i < gv.Controls.Count; i++)
        {
            if ((null != htControls[gv.Controls[i].GetType().Name]) || (null != htControls[gv.Controls[i].GetType().BaseType.Name]))
            {
                l.Text = GetControlPropertyValue(gv.Controls[i]);
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);
            }
            if (gv.Controls[i].HasControls())
            {
                PrepareGridViewForExport(gv.Controls[i]);
            }
        }
    }
    protected void LnkBtnWord_Click(object sender, EventArgs e)
    {
        GridView grd = (GridView)this.Parent.FindControl(GridviewControlId);
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Report.doc");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-word";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        HtmlForm frm = new HtmlForm();
        grd.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        if (!string.IsNullOrEmpty(HideColumns))
        {
            if (HideColumns.Contains(","))
            {
                string[] columns = HideColumns.Split(',');
                for (int i = 0; i < columns.Length; i++)
                {
                    grd.Columns[Convert.ToInt16(columns[i])].Visible = false;
                }
            }
            else
            {
                grd.Columns[Convert.ToInt16(HideColumns)].Visible = false;
            }
        }
        for (int i = 0; i < grd.Rows.Count; i++)
        {
            //System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)grd.Rows[i].Cells[grd.Columns.Count - 2].FindControl("imgitem");
            //img.Width = Unit.Pixel(60);
        }
        grd.Columns[grd.Columns.Count - 1].Visible = false;        
        
        grd.AllowPaging = false;
        //PrepareGridViewForExport(grd);
        frm.Controls.Add(grd);        
        frm.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    protected void LnkBtnCsv_Click(object sender, EventArgs e)
    {
        GridView grd = (GridView)this.Parent.FindControl(GridviewControlId);

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Report.csv");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/text";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        HtmlForm frm = new HtmlForm();
        grd.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        if (!string.IsNullOrEmpty(HideColumns))
        {
            if (HideColumns.Contains(","))
            {
                string[] columns = HideColumns.Split(',');
                for (int i = 0; i < columns.Length; i++)
                {
                    grd.Columns[Convert.ToInt16(columns[i])].Visible = false;
                }
            }
            else
            {
                grd.Columns[Convert.ToInt16(HideColumns)].Visible = false;
            }
        }
        //grd.Columns[5].Visible = false;
        PrepareGridViewForExport(grd);
        frm.Controls.Add(grd);
        frm.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    private string GetControlPropertyValue(Control control)
    {

        Type controlType = control.GetType();

        string strControlType = controlType.Name;

        string strReturn = "Error";

        bool bReturn;

 

        PropertyInfo[] ctrlProps = controlType.GetProperties();

        string ExcelPropertyName = (string)htControls[strControlType];

        if (ExcelPropertyName == null)

        {

            ExcelPropertyName = (string)htControls[control.GetType().BaseType.Name];

            if (ExcelPropertyName == null)

                return strReturn;

        }

        foreach (PropertyInfo ctrlProp in ctrlProps)

        {

            if (ctrlProp.Name == ExcelPropertyName &&

            ctrlProp.PropertyType == typeof(String))

            {

                try

                {

                    strReturn = (string)ctrlProp.GetValue(control, null);

                    break;

                }

                catch

                {

                    strReturn = "";

                }

            }

            if (ctrlProp.Name == ExcelPropertyName &&

            ctrlProp.PropertyType == typeof(bool))

            {

                try

                {

                    bReturn = (bool)ctrlProp.GetValue(control, null);

                    strReturn = bReturn ? "True" : "False";

                    break;

                }

                catch

                {

                    strReturn = "Error";

                }

            }

            if (ctrlProp.Name == ExcelPropertyName &&

            ctrlProp.PropertyType == typeof(System.Web.UI.WebControls.ListItem))

            {

                try

                {

                    strReturn = ((System.Web.UI.WebControls.ListItem)(ctrlProp.GetValue(control, null))).Text;

                    break;

                }

                catch

                {

                    strReturn = "";

                }

            }

        }

        return strReturn;

    }
}
